/**
 * 画图层
 */
var Canvas = require('canvas'),
	async = require('async'),
	fs = require('fs'),
	path = require('path'),
	mkdirp = require('mkdirp'),
	PencilData = require('./PencilData'),
	ToolRedoUndo = require('./ToolRedoUndo'),
	Pager = require('./Pager/main'),
	config = require('../../config');

	require('node-easel');

	var Layer = function() {
		//常用标识
		this.canvasEle = false;
		this.container = false;
		this.imgObj = false;

		this.canvasWidth = false;
		this.canvasHeight = false;

		this.toolRedoUndo = new ToolRedoUndo();
		this.pencilData = new PencilData();

		//私有标识
		this._imgIndex = 0;
		this._pagers = [];
		this._currentPage = 0;

		/**
		 * 初始化方法
		 * @param {Object} imgObj 图片对象属性有img,fileOrPpt
		 */
		this.init = function(imgObj) {
			this.canvasEle = new Canvas(config.screenWidth, config.screenHeight);
			this.canvasWidth = config.screenWidth;
			this.canvasHeight = config.screenHeight;

			this.container = new createjs.Stage(this.canvasEle);
			this._pagers[0] = new Pager(this.canvasWidth,this.canvasHeight,this.pencilData);
			this._pagers[0].init();
			this.container.addChild(this._pagers[0].container);

			this.imgObj = imgObj;

			//bug-初始化画笔
			this.pencilData.setPainterColor({"r":0.000000, "g":0.000000, "b":0.000000, "a":1.000000});
			this.pencilData.setPainterLineWidth(5);
			this.pencilData.setPainterMode(0);
		}

		/**
		 * 画图方法
		 * @param {Array} records 操作节点
		 * @param {Function} callback
		 * @param {bool} isSavePage  是否保存到最后一张
		 */
		this.draw = function(records,callback,isSavePage) {
			var success = false;
			async.each(records, function(obj, cb) {
				success = function(obj) {
					if(obj){
						this.pushObj2UndoStack(obj);
					}
					cb();
				}.bind(this);

				this.handelRecords("normal", obj,success);


			}.bind(this), function(err) {
				if(err){
					callback(err);
					return;
				}

				async.waterfall([
					function(cb){
						this.container.update();
						cb(null);
					}.bind(this),
					function (cb) {
						mkdirp(path.join(config.tmpPath, 'imageData'), function(err) {
							var writeStream = fs.createWriteStream(path.join(config.tmpPath, 'imageData',this._imgIndex+'.jpg'));
							cb(null,writeStream);
						}.bind(this));
					}.bind(this),
					function(writeStream,cb){
						var readStream = this.canvasEle.jpegStream({
							bufsize: 4096
							, quality: 85
							, progressive: false
						});
						readStream.pipe(writeStream);
						cb();
					}.bind(this)
				],function(err){
					if(isSavePage){
						this.saveCurrentPageImage();
					}

					this._imgIndex++;
					callback(err);
				}.bind(this));
			}.bind(this));
		}


		//绘制undo列表中的
		this._pringUndoList = function() {
			this.clearAllCanvas();
			var records = this.toolRedoUndo.undo_stack.get_stack();
			async.each(records, function(subRecords, cb) {
				async.each(subRecords,function(obj,callback){
					this.handelRecords("pringUndo",obj,callback);
				}.bind(this),function(err){
					cb();
				}.bind(this));
			}.bind(this), function(err) {
				this.container.update();
				if(err)
					console.error('err: ' + err);
			}.bind(this));

		}

		//清除所有轨迹
		this.clearAllCanvas = function() {
			this.container.removeAllChildren();
			this._pagers = [];
			this._currentPage = 0;
			this._pagers[0] = new Pager(this.canvasWidth,this.canvasHeight,this.pencilData);
			this._pagers[0].init();
			this.container.addChild(this._pagers[0].container);
		}

		/**
		 * records助手
		 * @param {String} handelType 助手类型（normal:正常解析/pringUndo:在undo列表中解析/）
		 * @param {obj} Object 要解析的对象
		 * @param {Function} success 成功的回调
		 */
		this.handelRecords = function(handelType, obj,success) {
			switch (obj.class) {
				case "DRContextRecord":
					var type = obj.type;
					switch (type) {
						case 1: //设置画笔颜色
							this.pencilData.setPainterColor(obj.data);
							success && success(obj);
							break;
						case 2: //设置画笔粗细
							this.pencilData.setPainterLineWidth(obj.data);
							success && success(obj);
							break;
						case 3: //设置混合模式（正常或者擦除）
							this.pencilData.setPainterMode(obj.data);
							success && success(obj);
							break;
						case 4: //插入空白页
							this.saveCurrentPageImage(function(){
								this.container.removeAllChildren();
								var mPager = new Pager(this.canvasWidth,this.canvasHeight,this.pencilData);
								mPager.init();
								this._pagers.splice(++this._currentPage, 0, mPager);
								this.container.addChild(this._pagers[this._currentPage].container);
								//保留对象
								if(obj.data == 0){
									this._pagers[this._currentPage].bgLayer.setBg(this._pagers[this._currentPage-1].bgLayer.getBg());
									this._pagers[this._currentPage].imgLayer.setImgs(this._pagers[this._currentPage-1].imgLayer.getImgs());
								}
								success(obj);
							}.bind(this));

							break;
						case 5: //幻灯片翻到下一页
							this.saveCurrentPageImage(function(){
								this.container.removeAllChildren();
								if(!this._pagers[++this._currentPage]){
									this._pagers[this._currentPage] = new Pager(this.canvasWidth,this.canvasHeight,this.pencilData);
									this._pagers[this._currentPage].init();
								}
								this.container.addChild(this._pagers[this._currentPage].container);
								success(obj);
							}.bind(this));
							break;
						case 6: //幻灯片翻到上一页
							this.saveCurrentPageImage(function(){
								this.container.removeAllChildren();
								if(!this._pagers[--this._currentPage]){
									this._pagers[this._currentPage] = new Pager(this.canvasWidth,this.canvasHeight,this.pencilData);
									this._pagers[this._currentPage].init();
								}
								this.container.addChild(this._pagers[this._currentPage].container);
								success(obj);
							}.bind(this));
							break;
						default:
							switch (handelType){
								case "normal":
									success(obj);
									break;
								default:
									success();
									break;
							}
				
							break;
					}
					break;
				case "DRStrokeRecord":
					this._pagers[this._currentPage].pencilDraw(obj,success);
					break;
				case "DRClearCanvasRecord":
					this._pagers[this._currentPage].clearPencil();
					success && success(obj);
					break;
				case "DRFileRecord":
					this.handleFile(obj);
					success && success(obj);
					break;
				case "DRRevokeRecord":
					switch (handelType){
						case "normal":
							this.toolRedoUndo.undo(obj, this._pringUndoList.bind(this), success);
							break;
						default:
							success && success();
						break;
					}
					break;
				case "DRRedoRecord":
					switch (handelType){
						case "normal":
								this.toolRedoUndo.redo(obj, this._pringUndoList.bind(this), success);
								break;
						default:
							success && success();
						break;
					}
					break;
				default:
					success && success();
					break;
			}
		}

		//图片助手
		this.handleFile = function(obj) {
			var relativeSourcePath = obj.relativeSourcePath;
			var img = null;
			obj.fileType = parseInt(obj.fileType);
			switch (obj.fileType){
				case 1://1是图片
					img = this.imgObj.img[relativeSourcePath];
					if (img.complete) {
						obj.imageObj = img;
						this._pagers[this._currentPage].drawImg(obj);
					} else
						console.error("读取图片失败！！");
					break;
				case 2://2是资源
					img = this.imgObj.fileOrPpt[relativeSourcePath];
					if (img.complete) {
						obj.imageObj = img;
						this._pagers[this._currentPage].drawImg(obj);
					} else
						console.error("读取图片失败！！");
					break;
				case 3://3是背景
					img = this.imgObj.fileOrPpt[relativeSourcePath];
					if (img.complete) {
						obj.imageObj = img;
						this._pagers[this._currentPage].drawBg(obj);
					} else
						console.error("读取文件或者ppt失败！！");
					break;
				default :
					break;
			}
		}

		/**
		 * 保存当前页到文件夹
		 */
		this.saveCurrentPageImage = function(callback){
			async.waterfall([
				function(cb){
					this.container.update();
					cb(null);
				}.bind(this),
				//页保存目录
				function (cb) {
					mkdirp(path.join(config.tmpPath, 'note'), function(err) {
						var writeStream = fs.createWriteStream(path.join(config.tmpPath, 'note','page'+this._currentPage+'note.jpg'));
						cb(null,writeStream);
					}.bind(this));
				}.bind(this),
				function(writeStream,cb){
					var readStream = this.canvasEle.jpegStream({
						bufsize: 4096
						, quality: 85
						, progressive: false
					});
					readStream.pipe(writeStream);
					cb();
				}.bind(this)
			],function(err){
				callback && callback(err);
			}.bind(this));
		}
		
		//将轨迹加入到栈中
		this.pushObj2UndoStack = function(obj) {
			switch (obj.class){
				case "DRStrokeRecord":
					this._tmpObj || ( this._tmpObj = [] );
					this._tmpObj.push( obj );
					if( obj.phase == "2" ){
						this.toolRedoUndo.undo_stack.push( this._tmpObj );
						this.toolRedoUndo.redo_stack.clear();
						this._tmpObj = void 0;
					}
					break;
				case "DRContextRecord":
					this._tmpObj || ( this._tmpObj = [] );
					this._tmpObj.push( obj );
					break;
				case "DRFileRecord":
				case "DRClearCanvasRecord":
					this._tmpObj || ( this._tmpObj = [] );
					this._tmpObj.push( obj );
					this.toolRedoUndo.undo_stack.push( this._tmpObj );
					this.toolRedoUndo.redo_stack.clear();
					this._tmpObj = void 0;
				default:
					break;
			}
		}
	};
module.exports = Layer;